from rest_framework.generics import ListAPIView, CreateAPIView
from api.serializer.bid import BidModelSerializer
from api import models
from django.db.models import Max
from api.authentication.auth import UserAuthentication
from django.db import transaction
from rest_framework import exceptions


class BidView(ListAPIView, CreateAPIView):
    authentication_classes = [UserAuthentication]
    queryset = models.BidRecord.objects
    serializer_class = BidModelSerializer

    def get_queryset(self):
        item_id = self.request.query_params.get('item_id')
        return self.queryset.filter(item_id=item_id)

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        item_id = self.request.query_params.get('item_id')
        item_object = models.AuctionItem.objects.filter(id=item_id).first()
        max_price = self.queryset.filter(item=item_object).aggregate(max_price=Max('price'))['max_price']
        result = {
            "unit": item_object.unit,
            "price": max_price or item_object.start_price,
            'bid_list': response.data

        }
        response.data = result
        return response

    def perform_create(self, serializer):
        serializer.save(user_id=self.request.user.id, status=1)
